from xingchen import Configuration, ApiClient, ChatApiSub, ChatReqParams, CharacterKey, Message, UserProfile, ModelParameters, AdvancedSettings
from db.mongo import mongo
from db.mysql import mysql
from datetime import datetime
from core.config import settings
from db.crud.agent import get_agent_by_userid
class ChatService:
    def __init__(self):
        self.api_client = self._init_xingchen_client()
        
    def _init_xingchen_client(self):
        # 从配置获取实际值
        configuration = Configuration(
            host="https://nlp.aliyuncs.com",
            access_token=settings.XINGCHEN_API_KEY
        )
        return ChatApiSub(ApiClient(configuration))
    async def process_chat(self, username, agent_profile, history, message):
        # print(agent_profile)
        chat_params = ChatReqParams(
            bot_profile=CharacterKey(
                name=agent_profile["name"],
                content=self._build_character_content(agent_profile),
                traits="保持礼貌的态度，没有回复字数限制，根据具体问题回答"
            ),
            model_parameters=ModelParameters(
                model_name="xingchen-plus-v2",
                top_p=0.95,
                temperature=0.92
            ),
            messages=history + [
                Message(
                    role="user",
                    content=message
                )
            ],
            user_profile=UserProfile(
            user_id='123456789',
            user_name=username
        ),
        )
    
     
        import asyncio
        response = await asyncio.to_thread(self.api_client.chat, chat_params)
        return response
    async def create_chat_response(self, user_id: str, session_id: str, message: str, username: str):
        try:
            # 1. 保存用户消息
            await mongo.save_chat_message({
                "userId": user_id,
                "sessionId": session_id,
                "role": "user",
                "content": message,
                "username": username,
                "createdAt": datetime.now()
            })
            
            # 2. 获取AI人设配置
            agent_profile = await get_agent_by_userid(user_id)
         
            # 3. 获取最近5条历史
            history = await mongo.get_recent_chat_history(user_id, session_id)
            
            response = await self.process_chat(username, agent_profile, history, message)
            ai_reply = response.data.choices[0].messages[0].content
            token_used = response.data.usage.input_tokens + response.data.usage.output_tokens
            
            # 6. 保存AI回复
            await mongo.save_chat_message({
                "userId": user_id,
                "sessionId": session_id,
                "role": "assistant",
                "content": ai_reply,
                "username": username,
                "createdAt": datetime.now()
            })
            
            return {
                "content": ai_reply,
                "totalToken": token_used
            }
            
        except Exception as e:
            # 错误处理逻辑
            raise e
    
    def _build_character_content(self, profile) -> str:
        return f"""
        【你的人设】
        姓名：{profile["name"]}
        性别：{profile["gender"]}
        年龄：{profile["age"]}
        别名：{profile["alias"]}
        籍贯：{profile["placeOfOrigin"]}
        职业：{profile["profession"]}
        性格：{profile["style"]}

        目标：{profile["goal"]}
        注意事项：{profile["notes"]}
        对话样例：{profile["template"]}
        """
    # 根据userId和sessionId获取聊天记录
    async def get_chat_history(self, user_id: str, session_id: str):
        return await mongo.get_chat_history(user_id, session_id)
    # 根据userId和sessionId清空聊天记录
    async def clear_chat_history(self, user_id: str, session_id: str):
        return await mongo.clear_chat_history(user_id, session_id)
    
    # 获取用户的所有对话记录
    async def get_user_all_sessions(self, user_id: str):
        """获取用户的所有对话会话列表"""
        return await mongo.get_user_all_sessions(user_id)